/*
 *  Copyright (C) 2010 jp
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.boc.botv.web.validator;

import com.boc.botv.model.User;
import com.boc.botv.service.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 *
 * @author jp
 */
@Component("userValidator")
public class UserValidator implements Validator {

  @Autowired
  private UserManager userManager;

  public boolean supports(Class clazz) {
    throw new UnsupportedOperationException("Not supported yet.");

  }

  public void validate(Object obj, Errors errors) {
    User u = (User) obj;
    if (u != null) {
      if (u.getLogin() != null && u.getLogin().length() < 4) {
        errors.rejectValue("login", "validation.login", "4 caractères minimum.");
      }
      if (u.getPassword() != null && u.getPassword().length() < 4) {
        errors.rejectValue("password", "validation.password", "4 caractères minimum.");
      }
      if (!u.isTermsAccepted()) {
        errors.rejectValue("termsAccepted", "validation.termsAccepted", "Vous devez accepter les CGU pour vous inscrire.");
      }

      if (userManager.loginExists(u.getLogin())) {
        errors.rejectValue("login", "validation.login", "Ce pseudo n'est pas disponible.");
      }
      if (userManager.mailExists(u.getPassword())) {
        errors.rejectValue("email", "validation.email", "Ce courriel est déjà utilisé.");
      }
      if (u.getPassword() != null && u.getCheckPassword() != null && !u.getPassword().equals(u.getCheckPassword())) {
        System.out.println(u.getPassword() + " = " + u.getCheckPassword());
        errors.rejectValue("password", "validation.password", "Les mots de passe entrés ne correspondent pas.");
      }
    }
  }
}
